import React, { useCallback, useEffect, useState } from 'react';
import NavBar from '@/components/NavBar/NavBar';
import SvgIcon from '@/components/SvgIcon/SvgIcon';
import Radio from '@/components/Radio/Radio';
import doctor from '@/assets/images/avatar-doctor.svg';
import { Link, useNavigate } from 'react-router-dom';
import { Button, ImageUploader, ImageUploadItem, Input, NoticeBar, TextArea, Toast } from 'antd-mobile';
import { flagOptions, timeOptions } from '@/constants/constult';
import type { ConsultIllness as ConsultIllnessInfo } from '@/type/ConsultType';
import { useEnhanceDispatch } from '@/hooks';
import { setConsultIllnessInfo, upload } from '@/store/modules/consultStore';
import type { UploadResponse } from '@/API/commonAPI';
import './ConsultIllness.scss';
import Upload from '@/components/Upload/Upload';


const ConsultIllness = () => {
  const demoLongText = '请描述你的疾病或症状、是否用药、就诊经历，需要我听过什么样的帮助';

  const navigate = useNavigate();
  const enhanceDispatch = useEnhanceDispatch();
  // 左边插槽内容
  const left = useCallback(() => (<span>返回</span>), []);
  // 中间插槽内容
  const children = useCallback(() => (<span>图文问诊</span>), []);
  // 右边插槽内容
  const right = useCallback(() => (<Link to="/">问诊记录</Link>), []);
  // 图片列表
  const [fileList, setFileList] = useState<ImageUploadItem[]>([]);
  // 图文问诊的表单数据
  const [consultIllness, setConsultIllness] = useState<ConsultIllnessInfo>({
    illnessDesc: '',
    illnessTime: 1,
    consultFlag: 1,
    pictures: [],
  });

  /**
   *@description 已上传的文件列表变化时触发的回调函数
   * */
  const onChangeFieList = (uploads: ImageUploadItem[]) => {
    setFileList(uploads);
  };

  /**
   * @description上传的回调函数，入参是需要被上传的文件对象，经过异步处理之后，返回上传结果
   * */
  const onUpload = async (file: File) => {
    const formData = new FormData();
    formData.append('file', file);
    const uploadResponse: UploadResponse = await enhanceDispatch(upload(formData)).unwrap();
    return uploadResponse;
  };

  /**
   *@description 文件读取前的回调函数，返回null可终止文件读取，支持返回 Promise
   * */
  const beforeUpload = (file: File) => {
    if (file.size > 1024 * 1024) {
      Toast.show('请选择小于 1M 的图片');
      return null;
    }
    return file;
  };

  /**
   *@description 点击下一步按钮的回调函数 记录病情描述并且跳转到患者列表页面
   * */
  const handleNext = () => {
    enhanceDispatch(setConsultIllnessInfo(consultIllness));
    navigate(`/patient?selected=Fast`);
  };

  /**
   *监听fileList数组的变化，收集参数准备带给服务器
   * */
  useEffect(() => {
    setConsultIllness({ ...consultIllness, pictures: fileList as { id: string, url: string }[] });
  }, [fileList]);

  return (
    <div className="consult-illness">
      {/*导航栏组件*/}
      <NavBar back={left()} children={children()} right={right()} onBack={() => navigate(-1)}></NavBar>
      <NoticeBar content={demoLongText} color="alert" />
      {/*医生提示*/}
      <div className="illness-tip">
        <img className="img" src={doctor} />
        <div className="info">
          <p className="tit">在线医生</p>
          <p className="tip">请描述你的疾病或症状、是否用药、就诊经历，需要我听过什么样的帮助</p>
          <p className="safe">
            <SvgIcon name="safe" width="15px" height="15px" /><span>内容仅医生可见</span>
          </p>
        </div>
      </div>
      {/*收集信息*/}
      <div className="illness-form">
        <div className="item">
          <p>患者病情描述</p>
          <TextArea style={{ '--font-size': '14px' }} showCount placeholder="请详细描述您的病情，病情描述不能为空" rows={3} value={consultIllness.illnessDesc} onChange={(illnessDesc: string) => {
            setConsultIllness({ ...consultIllness, illnessDesc });
          }} />
        </div>
        <div className="item">
          <p>本次患病多久了?</p>
          <Radio optionsList={timeOptions} value={consultIllness.illnessTime} onChange={(illnessTime: number) => {
            setConsultIllness({ ...consultIllness, illnessTime });
          }}></Radio>
        </div>
        <div className="item">
          <p>此次病情是否去医院就诊过?</p>
          <Radio optionsList={flagOptions} value={consultIllness.consultFlag} onChange={(consultFlag: number) => {
            setConsultIllness({ ...consultIllness, consultFlag: consultFlag as 0 | 1 });
          }}></Radio>
        </div>
        <div className="item">
          <p>请上传病情图片</p>
          <ImageUploader maxCount={3} value={fileList} onChange={onChangeFieList} upload={onUpload} beforeUpload={beforeUpload}></ImageUploader>
        </div>
        <div className="item">
          <p>上传病例信息</p>
          <Upload fileList={fileList} setFileList={(uploads) => setFileList(uploads)}></Upload>
        </div>
        <div className="item">
          <Button color="primary" onClick={handleNext}>下一步</Button>
        </div>
      </div>
    </div>
  );
};

export default ConsultIllness;